<template>
  <div>
    <div class="bg-light">
      <div class="container-title">销售属性</div>
      <div>
        <Form :model="setsForm" :label-width="100">
          <FormItem v-for="(item, index) in saleAttrs" :key="index" :label="item.label">
            <CheckboxGroup v-model="setsForm[index]">
              <Checkbox v-for="inner in item.checkbox" :key="inner.id" :label="inner.id" :disabled="checkIfDisabled(index, inner.id)">{{ inner.value }}</Checkbox>
            </CheckboxGroup>
          </FormItem>
        </Form>
        <div v-if="setsForm.hw.length > 0 || setsForm.gz.length > 0" class="sets-table">
          <table style="table-layout: fixed">
            <tr class="thead">
              <th v-if="setsForm.hw.length>0">{{ saleAttrs.hw.label }}</th>
              <th v-if="setsForm.gz.length>0">{{ saleAttrs.gz.label }}</th>
              <th v-if="isImage"><span>*</span>图片</th>
              <th><span>*</span>建议零售价</th>
              <th><span>*</span>基础批发价</th>
              <th>开票价</th>
              <th>库存</th>
              <th><span>*</span>SKU编码</th>
              <th>SKU条码</th>
            </tr>
            <tr v-for="(item, i) in tableData" :key="i" class="tright-body">
              <td v-if="setsForm.hw.length>0" v-show="item.isShow" :rowspan="item.rowspan">{{ getHwVal(item.hw) }}</td>
              <td v-if="setsForm.gz.length>0">{{ getGzVal(item.gz) }}</td>
              <td v-if="isImage" v-show="item.isShow" :rowspan="item.rowspan">
                <div v-if="isLook" class="pnl upload-list ghost-upload">
                  <div v-for="(m, index) in item.uploadList" v-show="m.imgUrl" :key="index" class="item ghost-item">
                    <a :href="preFixPath + m.imgUrl" target="_blank"><img :src="preFixPath + m.imgUrl + '_110w'"></a>
                  </div>
                </div>
                <PictureGhostEditItem v-else :index="i" :upload-list="item.uploadList" @uploadPic="setImg" />
              </td>
              <td><Input v-model.trim="item.marketPrice" :disabled="productId||flag?true:isLook" @on-blur="onBlur($event,'marketPrice',i)" @on-change="modelData($event,'marketPrice',i)" /></Input></td>
              <td><Input v-model.trim="item.sale" :disabled="isLook" @on-blur="onBlur($event,'sale',i)" @on-change="modelData($event,'sale',i)" /></Input></td>
              <td><Input v-model.trim="item.invoice" :disabled="isLook" @on-blur="onBlur($event,'invoice',i)" @on-change="modelData($event,'invoice',i)" /></Input></td>
              <td><Input v-model.trim="item.stock" :disabled="isLook" @on-blur="onBlur($event,'stock',i)" @on-change="modelData($event,'stock',i)" /></Input></td>
              <td><Input v-model.trim="item.code" :maxlength="30" :disabled="productId||flag?true:isLook" @on-blur="onBlur($event,'code',i)" @on-change="modelData($event,'code',i)" /></Input></td>
              <td><Input v-model.trim="item.proCode" :maxlength="20" :disabled="isLook" @on-blur="onBlur($event,'proCode',i)" @on-change="modelData($event,'proCode',i)" /></Input></td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <!-- 线上修改撤回 -->
    <div class="bg-light pb">
      <div class="container-title">SKU图片</div>
      <div class="sku-containter">
        <div v-for="(item,index) in tableData" :key="index" class="sku-box">
          <div class="sku-title">
            <p v-if="item.hwName" class="e1 font-blue">{{ item.hwName }}</p>
            <p v-if="item.gzName" class="e1 font-blue">{{ item.gzName }}</p>
          </div>
          <div v-if="isLook" class="main-pic">
            <a :href="preFixPath + item.skuImgArr[0].imgUrl" target="_blank"><img :src="preFixPath + item.skuImgArr[0].imgUrl + '_110w'"></a>
          </div>
          <PictureEditItem v-else :upload-list="item.skuImgArr" :item-data="item" @uploadPic="uploadSkuPic" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import PictureGhostEditItem from './PictureGhostEditItem'
import PictureEditItem from './PicUpload'
import { preFixPath } from '@/util'
export default {
  components: {
    PictureGhostEditItem,
    PictureEditItem
  },
  props: {
    productType: String,
    productId: String,
    isLook: {
      type: Boolean,
      default: false
    },
    flag: {
      type: Boolean,
      default: false
    },
    centerProductSkuArr: Array
  },
  data () {
    const validateCode = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入商品SKU编码'))
      } else {
        if (!/^[A-Za-z0-9/\-]+$/.test(value)) {
          callback(new Error('只能输入数字和英文字符和/-'))
        } else if (value.length < 2 || value.length > 30) {
          callback(new Error('SKU编码的长度在2-30之间'))
        } else {
          callback()
        }
      }
    }
    const validateBarcode = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else {
        if (!/^[A-Za-z0-9]+$/.test(value)) {
          callback(new Error('只能输入数字和英文字符'))
        } else if (value.length < 2 || value.length > 20) {
          callback(new Error('SKU条码的长度在2-20之间'))
        } else {
          callback()
        }
      }
    }
    const validateStock = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else {
        if (!/^(0|[1-9]\d*)$/.test(value)) {
          callback(new Error('只能输入0或者正整数'))
        } else {
          callback()
        }
      }
    }
    const validateNumber = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入数字'))
      } else {
        if (!/(^[1-9]\d{0,8}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(value)) {
          callback(new Error('只能输入九位整数或者两位小数'))
        } else {
          callback()
        }
      }
    }
    const validateCostNumber = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else {
        if (!/(^[1-9]\d{0,8}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(value)) {
          callback(new Error('只能输入九位整数或者两位小数'))
        } else {
          callback()
        }
      }
    }
    return {
      preFixPath,
      tire_ratioArr: [],
      tire_sizeArr: [],
      tire_widthArr: [],
      isFirst: 1,
      isImage: false, //是否有上传图片按钮
      form: {
        tireWidth: '',
        tireAspectRatio: '',
        tireRim: '',
        code: '',
        barcode: '',
        marketPrice: null,
        salePrice: null,
        invoicePrice: null,
        stock: null
      },
      ruleValidate: {
        tireWidth: [
          { required: true, message: '请选择胎面宽', trigger: 'change' }
        ],
        tireAspectRatio: [
          { required: true, message: '请选择扁平率', trigger: 'change' }
        ],
        tireRim: [{ required: true, message: '请选择直径', trigger: 'change' }],
        code: [{ required: true, validator: validateCode, trigger: 'blur' }],
        barcode: [{ validator: validateBarcode, trigger: 'blur' }],
        marketPrice: [
          { required: true, validator: validateNumber, trigger: 'blur' }
        ],
        salePrice: [
          { required: true, validator: validateNumber, trigger: 'blur' }
        ],
        invoicePrice: [{ validator: validateCostNumber, trigger: 'blur' }],
        stock: [{ validator: validateStock, trigger: 'blur' }]
      },
      setsForm: {
        gz: [],
        hw: []
      },
      tableData: [],
      serverData: [],
      saleAttrs: {}
    }
  },
  computed: {
    centerProductSku () {
      let arr = {
        gz: [],
        hw: []
      }
      this.centerProductSkuArr.forEach(item => {
        if (arr.gz.indexOf(item.gz) < 0) arr.gz.push(item.gz)
        if (arr.hw.indexOf(item.hw) < 0) arr.hw.push(item.hw)
      })
      return arr
    }
  },
  watch: {
    setsForm: {
      handler (c, o) {
        if (c.gz.length > 0 && c.hw.length > 0) {
          let newGroupArr = []
          if (this.isFirst == 1) {
            newGroupArr = JSON.parse(JSON.stringify(this.serverData))
            this.isFirst = 2
          } else {
            newGroupArr = JSON.parse(JSON.stringify(this.tableData))
          }
          this.tableData = []
          //是否显示图片
          let hwImage = false
          let gzImage = false
          hwImage = this.saleAttrs.hw.isImage
          gzImage = this.saleAttrs.gz.isImage
          if (hwImage || gzImage) {
            this.isImage = true
          } else {
            this.isImage = false
          }
          let group = this.dgArray(c.hw, c.gz)
          group.forEach((item, i) => {
            group[i] = {
              hw: group[i].hw,
              gz: group[i].gz,
              hwName: this.getHwVal(group[i].hw),
              hwParentId: this.saleAttrs.hw.id,
              hwParentName: this.saleAttrs.hw.label,
              gzParentName: this.saleAttrs.gz.label,
              uploadList: [],
              marketPrice: '',
              sale: '',
              invoice: '',
              stock: '',
              proCode: '',
              code: '',
              rowspan: group[i].rowspan,
              isShow: group[i].isShow,
              skuImgArr: [] // sku主图
            }
            if (group[i].gz) {
              group[i].gzName = this.getGzVal(group[i].gz)
              group[i].gzParentId = this.saleAttrs.gz.id
            }
            newGroupArr.map((data, j) => {
              if (data.hw == item.hw && data.gz == item.gz) {
                data.rowspan = group[i].rowspan
                data.isShow = group[i].isShow
                group[i] = Object.assign(group[i], data)
              }
            })
            this.serverData.map((data, j) => {
              if (data.hw == item.hw && data.gz == item.gz) {
                for (let key in group[i]) {
                  if ((!group[i][key] && key !== 'isShow' && key !== 'rowspan') || (Array.isArray(group[i][key]) && group[i][key].length === 0)) {
                    group[i][key] = data[key]
                  }
                }
              }
            })
            this.centerProductSkuArr.map((data, j) => {
              if (data.hw == item.hw && data.gz == item.gz) {
                for (let key in group[i]) {
                  if (!group[i][key] || (Array.isArray(group[i][key]) && group[i][key].length === 0)) {
                    group[i][key] = data[key]
                  }
                }
              }
            })
          })
          this.tableData = group
          //编辑时，再增加一行，把img的值传进去
          // let alreadyImg = "";
          // this.tableData.forEach(item => {
          //   if (item.img != "") {
          //     alreadyImg = item.img;
          //   }
          //   item.img = alreadyImg;
          // });
        }

        if (c.hw.length === 0 || c.gz.length === 0) {
          let newArr = []
          if (this.isFirst == 1) {
            newArr = JSON.parse(JSON.stringify(this.serverData))
            this.isFirst = 2
          } else {
            newArr = JSON.parse(JSON.stringify(this.tableData))
          }
          this.tableData = []
          //是否显示图片
          let hwImage = false
          let gzImage = false
          if (c.hw.length > 0) hwImage = this.saleAttrs.hw.isImage
          if (c.gz.length > 0) gzImage = this.saleAttrs.gz.isImage
          if (hwImage || gzImage) {
            this.isImage = true
          } else {
            this.isImage = false
          }

          let _len = c.hw.length || c.gz.length

          for (var i = 0; i < _len; i++) {
            let _obj = {
              hw: c.hw[i],
              gz: c.gz[i],
              marketPrice: '',
              sale: '',
              invoice: '',
              stock: '',
              code: '',
              proCode: '',
              isShow: true,
              uploadList: [],
              skuImgArr: [] // sku主图
            }
            newArr.map(res => {
              if ((res.hw === _obj.hw && res.hw) || (res.gz === _obj.gz && res.gz)) {
                _obj.uploadList = res.uploadList
                _obj.code = res.code
                _obj.sale = res.sale
                _obj.invoice = res.invoice
                _obj.stock = res.stock
                _obj.marketPrice = res.marketPrice
                _obj.proCode = res.proCode
              }
            })
            if (_obj.hw) {
              _obj.hwName = this.getHwVal(c.hw[i])
              _obj.hwParentId = this.saleAttrs.hw.id
              _obj.hwParentName = this.saleAttrs.hw.label
            }
            if (_obj.gz) {
              _obj.gzName = this.getGzVal(c.gz[i])
              _obj.gzParentId = this.saleAttrs.gz.id
              _obj.gzParentName = this.saleAttrs.gz.label
            }
            this.serverData.map((data, j) => {
              if (data.hw === c.hw[i] && data.gz === c.gz[i]) {
                for (let key in _obj) {
                  if (!_obj[key] || (Array.isArray(_obj[key]) && _obj[key].length === 0)) _obj[key] = data[key]
                }
              }
            })
            this.centerProductSkuArr.map((data, j) => {
              if (data.hw == c.hw[i] && data.gz == c.gz[i]) {
                for (let key in _obj) {
                  if (!_obj[key] || (Array.isArray(_obj[key]) && _obj[key].length === 0)) {
                    _obj[key] = data[key]
                  }
                }
              }
            })
            this.tableData.push(_obj)
          }
        }
      },
      deep: true
    }
  },
  mounted () {
    this.serverData = [
      // {
      //     hw:1,
      //     gz:4,
      //     img:'',
      //     sku:'1',
      //     sale:'1',
      //     cost:'11',
      //     stock:'',
      //     proCode:'',
      //     isStart:false
      // },
    ]
  },
  methods: {
    setInfoSale () {
      // 防止商品切换的时候，上一个商品的销售属性带过来
      this.setsForm.gz = []
      this.setsForm.hw = []
      this.serverData.forEach(res => {
        if (res.gz) {
          if (this.setsForm.gz.indexOf(res.gz) < 0) {
            this.setsForm.gz.push(res.gz)
          }
        }
        if (res.hw) {
          if (this.setsForm.hw.indexOf(res.hw) < 0) {
            this.setsForm.hw.push(res.hw)
          }
        }
      })
    },
    setImg (index, file) {
      this.$set(this.tableData[index], 'uploadList', [file])
      // this.tableData.forEach(item => {
      //   if (item.hw === this.tableData[index].hw) {
      //     item.img = file.imgUrl
      //   }
      // })
    },
    onBlur (e, c, i) {
      let v = e.srcElement.value
      if (c === 'marketPrice' || c === 'sale') {
        if (v === '' || v === null || v === undefined) {
          this.$Notice.warning({
            title: '提醒',
            desc: '请输入值'
          })
        } else {
          if (!/(^[1-9]\d{0,8}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(v)) {
            this.$set(this.tableData[i], c, '')
            this.$Notice.warning({
              title: '提醒',
              desc: '只能输入最多九位整数或者两位小数点'
            })
          }
        }
      } else if (c === 'code') {
        if (v === '' || v === null || v === undefined) {
          this.$Notice.warning({
            title: '提醒',
            desc: '请输入商品SKU编码'
          })
        } else {
          if (!/^[A-Za-z0-9\/-]+$/.test(v)) {
            this.$Notice.warning({
              title: '提醒',
              desc: '只能输入数字和英文字符和/-'
            })
            this.$set(this.tableData[i], c, '')
          } else if (v.length < 2 || v.length > 50) {
            this.$Notice.warning({
              title: '提醒',
              desc: 'SKU编码的长度在2-50之间'
            })
            this.$set(this.tableData[i], c, '')
          } else {
            let codeFlag = this.tableData.some((item, j) => item.code === v && i !== j)
            if (codeFlag) {
              this.$info('SKU编码不能重复')
              this.$set(this.tableData[i], c, '')
            } else {
              let currentId = this.tableData[i].id
              let param = {
                exclusiveId: currentId,
                code: v
              }
              if (currentId) {
                this.$ajaxGet(`/product/product_sku/code_is_exits`, param).then(data => {
                  if (data) {
                    this.$Notice.warning({
                      title: '提醒',
                      desc: '此SKU编码已存在'
                    })
                    this.$set(this.tableData[i], c, '')
                  }
                })
              }
            }
          }
        }
      } else if (c === 'proCode' || v === null || v === undefined) {
        if (v) {
          if (!/^[A-Za-z0-9]+$/.test(v)) {
            this.$Notice.warning({
              title: '提醒',
              desc: '只能输入数字和英文字符'
            })
            this.$set(this.tableData[i], c, '')
          } else if (v.length < 2 || v.length > 20) {
            this.$Notice.warning({
              title: '提醒',
              desc: '商品条码的长度在2-20之间'
            })
            this.$set(this.tableData[i], c, '')
          }
        }
      } else if (c === 'stock' || v === null || v === undefined) {
        if (v && !/^(0|[1-9]\d*)$/.test(v)) {
          this.$Notice.warning({
            title: '提醒',
            desc: '只能输入0或者正整数'
          })
          this.$set(this.tableData[i], c, '')
        }
      } else if (c === 'invoice' || v === null || v === undefined) {
        if (!/(^[1-9]\d{0,8}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(v)) {
          this.$Notice.warning({
            title: '提醒',
            desc: '只能输入最多九位整数或者两位小数点'
          })
          this.$set(this.tableData[i], c, '')
        }
      }
    },
    modelData (e, c, i) {
      let v = e.srcElement.value
      this.$set(this.tableData[i], c, v.toString())
    },
    setHwAndGz (h, g, i) {
      if (h) {
        this.$set(this.tableData[i], 'hw', h)
      }
      if (g) {
        this.$set(this.tableData[i], 'gz', g)
      }
    },
    getGzVal (id) {
      let o = this.saleAttrs.gz.checkbox.filter(res => {
        return res.id == id
      })
      return o[0] && o[0].value
    },
    getHwVal (id) {
      let o = this.saleAttrs.hw.checkbox.filter(res => {
        return res.id == id
      })
      return o[0] && o[0].value
    },
    dgArray (h, g) {
      let arr = []
      h.forEach((res, i) => {
        g.forEach((data, j) => {
          let o = {}
          o.gz = data
          o.hw = res
          o.rowspan = g.length
          o.isShow = j == 0
          arr.push(o)
        })
      })
      return arr
    },
    getSaleAttrs (obj) {
      // 防止商品切换的时候，上一个商品的销售属性带过来
      this.isFirst = 1
      // this.saleAttrs = obj // 不会触发视图更新
      this.$set(this, 'saleAttrs', obj)
      // this.saleAttrs = Object.assign({}, obj, this.saleAttrs) // 这样写也ok
    },
    uploadSkuPic (val, itemData) { // sku主图
      itemData.skuImgArr = val
      // if (itemData.hw && itemData.gz) {
      //   this.tableData.forEach(item => {
      //     if (item.hw === itemData.hw && item.gz === itemData.gz) item.skuImgArr = val
      //   })
      // } else if (itemData.hw) {
      //   this.tableData.forEach(item => {
      //     if (item.hw === itemData.hw) item.skuImgArr = val
      //   })
      // } else {
      //   this.tableData.forEach(item => {
      //     if (item.gz === itemData.gz) item.skuImgArr = val
      //   })
      // }
    },
    checkIfDisabled (index, id) {
      if (this.centerProductSku[index].length) {
        return this.isLook || this.centerProductSku[index].indexOf(id) < 0
      } else {
        return this.isLook
      }
    }
  }
}
</script>
